import { app, shell, BrowserWindow} from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
const fs = require('fs')
//注册接口,前端调用
import {registerIpcMain} from "./registerIpcMain"

//菜单
import { createMenu,createTray,isTrayQuit} from './munu'; // 导入 createMenu 函数

var mainWindow;

function createWindow(): void {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 670,
    show: false,
    autoHideMenuBar: false, //自动隐藏菜单
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      defaultEncoding: 'utf-8' //解决中文乱码
    }
  })

  //默认打开调试模式
  //mainWindow.webContents.openDevTools()

  //设置图标
  mainWindow.setIcon(icon);  

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  //创建窗口
  createWindow()

  //创建菜单
  createMenu()
  //创建托盘菜单
  createTray(mainWindow)

  //统一用一个ts文件映射icp接口，方便管理
  registerIpcMain.init(mainWindow);

  //当应用启动完成后,主动判断应用是否是从网页中调起
  _handleAfterReady()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  // 拦截关闭事件，并隐藏窗口
  mainWindow.on('close', (event) => {
    if (!isTrayQuit) {
      event.preventDefault(); // 阻止窗口关闭
      mainWindow?.hide(); // 隐藏窗口
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.



////////////////////////////////监听浏览器唤醒程序和接收参数//////////////////////////////////////
//设置监听协议名称,浏览器输入: etree-app://abc123 唤醒程序,其中abc123是自己拼接的参数
//在不关闭软件的情况下默认是可以多次唤醒的，并传入参数的
const protocolName='etree-app'
if (!app.isDefaultProtocolClient(protocolName)) {
  app.setAsDefaultProtocolClient(protocolName)
}
//当应用启动完成后,主动判断应用是否是从网页中调起
/**
window 下通过URL Schemes协议调起应用时分两种情况
(1)应用处于打开状态，会触发 second-instance 事件并接收这个 URL。
(2)应用处于未打开状态，在网页端通过浏览器调起应用之后不会触发 second-instance 事件；这个时候需要主动判断应用是否是从网页端调起，并主动触发 second-instance 事件；
在 window 里面判断是否是从网页端的标准：如果是通过url schema启动，其启动参数会超过1个
以下为在应用 ready 之后，判断是否是在 window 下主动调起客户端，并主动触发 second-instance 事件的实现逻辑；
*/
const _handleAfterReady = () => {
  // windows如果是通过url schema启动则发出时间处理
  // 启动参数超过1个才可能是通过url schema启动
  if (process.argv.length > 1) {
    if (!app.isReady()) {
      app.once("browser-window-created", () => {
        // app 未打开时，通过 open-url打开 app，此时可能还没 ready，需要延迟发送事件
        // 此段ready延迟无法触发 service/app/ open-url 处理，因为saga初始化需要时间
        app.emit("second-instance", null, process.argv);  //并主动触发 second-instance 事件
      });
    } else {
      app.emit("second-instance", null, process.argv); //并主动触发 second-instance 事件
    }
  }
};

//Electron 提供了一个简单的方法，来获取一个锁，只有第一个调用的实例才能获取成功，后面的其他实例则把参数传过去，然后退出就可以了
//win
const gotTheLock = app.requestSingleInstanceLock() 
if (!gotTheLock) {
  app.quit() //退出
} else {
  app.on('second-instance', (_event, argv) => { //接收传递参数argv是string[]数组
    //argv=C:\Program Files\image-manager\镜像管理系统.exe,--allow-file-access-from-files,--secure-schemes=app,--bypasscsp-schemes,--cors-schemes,--fetch-schemes,--service-worker-schemes,--standard-schemes=app,--streaming-schemes,etree-app://abc123/
    if (process.platform === 'win32' && argv.toString().indexOf('etree-app') >=0 ) { //浏览器启动的
      console.log(argv.toString())
      const str = argv[argv.length-1] //最后一个就是web传下来的参数 etree-app://abc123/
      const str1 = str.split('//')[1].split('/')[0]  
      fs.appendFile('C:/1111111.txt',str1+'\n','utf-8',() =>{
        console.log('save ok')
      })
    }else{ //本地启动的
      console.log("本地启动的")
    }
  })
}

// Mac
app.on('open-url', (_event, url) => {
  /** 向渲染进程传递唤醒参数 */
  mainWindow.webContents.send('awaken', { awakenArgs: decodeURI(url) })
});
////////////////////////////////监听浏览器唤醒程序和接收参数-结束//////////////////////////////////////